import {
  Controller,
  Delete,
  Get,
  Param,
  Query,
  UseGuards,
  UseInterceptors,
} from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import {
  OperUser,
  SystemUserDecoratorType,
} from 'src/decorator/operuser.decorator';
import { ReqType } from 'src/decorator/reqtype.decorator';
import { AuthItem, Code, OperType, Role } from 'src/global-type';
import { TokenGuard } from 'src/guard/token.guard';
import { AuthInterceptor } from 'src/interceptor/auth.interceptor';
import FileLogger from 'src/utils/file-logger';
import { handleParams } from 'src/utils/handle-params';
import { SystemLogService } from './system-log.service';
import { TargetType } from './utils';

const MODULETYPE = 'systemLog';

@ApiTags('系统日志')
@UseGuards(TokenGuard)
@Controller('api/system-log/v1.0.0')
export class SystemLogController {
  private readonly logger = new FileLogger(SystemLogController.name);

  constructor(private readonly systemLogService: SystemLogService) {}

  @ReqType(MODULETYPE, AuthItem.READ)
  @UseInterceptors(AuthInterceptor)
  @Get('/list')
  @ApiOperation({ summary: '查询系统日志' })
  async querySystemLogList(
    @Query() params,
    @OperUser() operUser: SystemUserDecoratorType,
  ) {
    try {
      const { data, sort } = handleParams(params, '-_id');
      if (operUser.role === Role.STAFF) data.userId = operUser._id;
      const res = await this.systemLogService.querySystemLogList(data, sort);
      this.systemLogService.insertSysLog(operUser, OperType.QUERY, {
        targetType: TargetType.systemLog,
        target: '列表',
        oldData: '',
        newData: '',
      });
      return {
        code: Code.OK,
        message: 'success',
        data: res,
      };
    } catch (err) {
      this.logger.printError(this.querySystemLogList.name, err);
      return {
        code: Code.UNKNOW_ERROR,
        message: String(err),
        data: {
          total: 0,
          data: [],
        },
      };
    }
  }

  @ReqType(MODULETYPE, AuthItem.DELETE)
  @UseInterceptors(AuthInterceptor)
  @Delete('/systemLog/:id')
  @ApiOperation({ summary: '删除系统日志' })
  async removeSystemLog(
    @Param('id') id: string,
    @OperUser() operUser: SystemUserDecoratorType,
  ) {
    try {
      const targetSystemLog = await this.systemLogService.findOneSystemLog({
        _id: id,
      });
      if (!targetSystemLog)
        return {
          code: Code.NOT_EXiST,
          message: '不存在的系统日志，请刷新后重试',
          data: null,
        };
      if (
        (targetSystemLog.ownerId !== operUser.ownerId &&
          operUser.role !== Role.ADMIN) ||
        (operUser.role === Role.STAFF && targetSystemLog.userId != operUser._id)
      )
        return {
          code: Code.UNAUTHORIZED,
          message: '不具备操作当前系统日志的操作权限，请联系管理员',
          data: null,
        };
      const res = await this.systemLogService.deleteOneSystemLog({ _id: id });
      if (!res)
        return {
          code: Code.UNKNOW_ERROR,
          message: '系统日志删除失败，请联系管理员进行处理',
          data: null,
        };
      this.systemLogService.insertSysLog(
        operUser,
        OperType.DELETE,
        {
          target: targetSystemLog._id,
          targetType: TargetType.systemLog,
          oldData: targetSystemLog ? JSON.stringify(targetSystemLog) : '',
          newData: '',
        },
        `操作描述为：[${targetSystemLog.description}]`,
      );
      return {
        code: Code.OK,
        message: 'success',
        data: null,
      };
    } catch (err) {
      this.logger.printError(this.removeSystemLog.name, err);
      return { code: Code.UNKNOW_ERROR, message: String(err), data: null };
    }
  }
}
